<template>
    <div class="app-container">
        <!-- 搜索 -->
    <div class="top-main"> 
    <el-form :model="queryParams" ref="queryRef" label-width="auto" :inline="true" class="top-form-fl stust">
      <el-form-item label="登录账号:"  prop="username">
        <el-input v-model="queryParams.username" placeholder="请输入登录账号" />
      </el-form-item>
      <el-form-item label="员工姓名:"  prop="nickname">
        <el-input v-model="queryParams.nickname" placeholder="请输入员工姓名" />
      </el-form-item>
      <el-form-item label="注册日期:" style="width: 400px;" prop="createStartTime">
        <el-col :span="11">
          <el-date-picker v-model="queryParams.createStartTime" type="date" placeholder="开始日期" style="width: 100%" />
        </el-col>
        <el-col :span="2" class="text-center">
          <span class="text-gray-500">-</span>
        </el-col>
        <el-col :span="11">
          <el-date-picker v-model="queryParams.createEndTime" type="date" placeholder="结束日期" style="width: 100%" />
        </el-col>
      </el-form-item>
      <el-form-item label="手机号:"  prop="mobile">
        <el-input v-model="queryParams.mobile" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="邮箱地址:"  prop="email">
        <el-input v-model="queryParams.email"  placeholder="请输入邮箱地址"/>
      </el-form-item>
    </el-form>
     <div class="top-from-fr">
        <el-button class="top-Search" @click="getUserList" type="primary">搜索</el-button>
        <el-button class="top-Refresh" @click="resetFrome">重置</el-button>
      </div>   
    </div>
        <!-- 新增用户 -->
        <div class="addUser">
            <el-button type="primary" icon="Plus" @click="setNewUser" style="float: right;">新增</el-button>
        </div>
          <Table v-bind="tableDta" style="width: 100%;" @deleteBox="deleteBox" @handleEdit="handleEdit" @handleSwitch="handleSwitch"
            @pageChange="tabPageChange"></Table>
        <!-- 新增用户弹窗 -->
        <el-dialog v-model="dialogVisible" :title="typeOpen==1 ? '新增用户':'编辑用户'" @close="cancel" width="700px">
            <el-form :model="form" label-width="auto" ref="userRef" :rules="rules" :inline="true">
                <el-form-item label="登陆账号:" prop="username">
                    <el-input :disabled="typeOpen!=1"  v-model="form.username" placeholder="请输入账号" />
                </el-form-item>
                <el-form-item label="登录密码:" v-if="typeOpen==1" prop="password">
                    <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password />
                </el-form-item>
                <el-form-item label="确认密码:" v-if="typeOpen==1" prop="confirmPassword">
                    <el-input v-model="form.confirmPassword" type="password" @blur="checkpassword" show-password />
                </el-form-item>
                <el-form-item label="所属权限:" prop="roleId">
                    <el-select v-model="form.roleId" multiple filterable allow-create default-first-option
                        :reserve-keyword="false" placeholder="请选择权限" style="width:190px">
                        <el-option v-for="item in rolePermissionList" :key="item.id" :label="item.name"
                            :value="item.id" />
                    </el-select>
                </el-form-item>
                <!-- <el-form-item label="账号类型:" prop="userType">
                    <el-select v-model="form.userType" placeholder="请选择账号类型" style="width:190px">
                        <el-option v-for="item in userTypeList" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item> -->
                <el-form-item label="所属职位:" prop="workPosition">
                    <el-input v-model="form.workPosition"></el-input>
                </el-form-item>
                <el-form-item label="所属部门:" prop="deptName">
                    <el-input v-model="form.deptName"></el-input>
                </el-form-item>
                <el-form-item label="员工姓名:" prop="nickname">
                    <el-input v-model="form.nickname"></el-input>
                </el-form-item>
                <el-form-item label="邮箱地址:" prop="email">
                    <el-input v-model="form.email" :disabled="typeOpen!=1" style="width:190px" />
                     <!-- <el-button :disabled="countdownEmail > 0" v-if="typeOpen==1" style="margin-left:20px" type="primary" @click="getCode('email')"> {{ countdownEmail > 0 ? countdownEmail + '秒' : '验证码' }}</el-button> -->

                </el-form-item>
                <el-form-item label="手机号:" prop="mobile">
                    <el-input v-model="form.mobile" placeholder="请输入手机号" style="width:190px" :disabled="typeOpen!=1" />
                     <el-button :disabled="countdownPhone > 0" v-if="typeOpen==1" style="margin-left:20px" type="primary" @click="getCode('phone')"> {{ countdownPhone > 0 ? countdownPhone + '秒' : '验证码' }}</el-button>

                </el-form-item>
                <el-form-item label="手机验证码:"  v-if="typeOpen==1" prop="smsCode">
                    <el-input v-model="form.smsCode">
                        <!-- <template #append>
                            <el-button @click="getCode('phone')" type="info">获取手机验证码</el-button>
                        </template> -->
                    </el-input>
                </el-form-item>
                
                <!-- <el-form-item label="邮箱验证码:"  v-if="typeOpen==1" prop="emailcode">
                    <el-input v-model="form.emailcode">
                    </el-input>
                </el-form-item> -->
            </el-form>
            <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitForm(userRef)">确 定</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
        </el-dialog>
      
    </div>
</template>
<script lang="ts" setup>
import { reactive, ref, onActivated ,toRefs} from 'vue';
import Table from '@/views/components/table/index.vue';
import { addUser, getRolePermission, getPhoneCode, getEmailCode, getUserPage, deleteUser, modifyStatus,getRoleDetailById,saveUserInfo } from '@/api/enterpriseManage/index';
import { ElMessage, ElMessageBox } from 'element-plus';
import {Plus,Delete,Edit} from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
const userRef=ref()
const rolePermissionList=ref([])
const userTypeList=ref([
        { label: '普通用户', value: 3 }
    ])
const data = reactive({
  form: {},
  queryParams: {
    username:'',
    nickname:'',
    mobile:'',
    examineStartTime:'',
    examineEndTime:'',
    createStartTime:'',
    createEndTime:'',
    email:'',
    pageNum: 1,
    pageSize: 10,
  },
  rules: {
        username: [
            { required: true, message: '请输入登录名', trigger: 'blur' },
            { min: 3, max: 32, message: '长度在3到32个字符', trigger: 'blur' },
            // { pattern: /^[a-zA-Z0-9]{3,32}$/, message: '必须包含大小写字母和数字', trigger: 'blur' }
        ],
         password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 8, max: 32, message: '长度在8到32个字符', trigger: 'blur' },
            { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur" }
            // { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@#$!%*?&])[A-Za-z\d@$!%*?&]{8,32}$/, message: '密码必须包含大小写字母、数字和特殊字符', trigger: 'blur' }
        ],  
         confirmPassword: [
            { required: true, message: '请输入登录确认密码', trigger: 'blur' },
            { min: 8, max: 32, message: '长度在8到32个字符', trigger: 'blur' },
             { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur" }

            // { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@#$!%*?&])[A-Za-z\d@$!%*?&]{8,32}$/, message: '密码必须包含大小写字母、数字和特殊字符', trigger: 'blur' }
        ],     
        roleId: [{ required: true, message: "请选择所属权限", trigger: "blur" }],
        userType: [{ required: true, message: "请选择账号类型", trigger: "blur" }],
        nickname: [{ required: true, message: "请输入员工姓名", trigger: "blur" }],
        mobile: [
            { required: true, message: '请输入手机号', trigger: 'blur' },
            { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        smsCode: [{ required: true, message: "请输入邮手机验证码", trigger: "blur" }],
        email: [
            { required: true, message: '请输入邮箱地址', trigger: 'blur' },
            { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        // emailcode: [{ required: true, message: "请输入邮箱验证码", trigger: "blur" }],

  }
});

const { queryParams, form, rules } = toRefs(data);
const tableDta = reactive({
    header: [
        { key: 'username', colWidth: '80', colheight: '80', title: '登陆账号', type: 'userName', isCheck: true },
        { key: 'nickname', colWidth: '80', title: '员工姓名', type: 'nickname', isCheck: true },
        { key: 'roleId', colWidth: '80', title: '角色', type: 'roleId', isCheck: true },
        { key: 'userType', colWidth: '80', title: '账号类型', type: 'userType', isCheck: true },
        { key: 'mobile', colWidth: '80', title: '手机号', type: 'mobile', isCheck: true },
        { key: 'email', colWidth: '100', title: '邮箱地址', type: 'email', isCheck: true },
        { key: 'createTime', colWidth: '100', title: '注册日期', type: 'createTime', isCheck: true },
        { key: 'status', colWidth: '60', title: '状态', type: 'status', isCheck: true },
        {
            key: 'operate',
            colWidth: '40',
            title: '操作',
            type: 'operate',
            isCheck: true,
            buttons: [
                {
                    icon: 'Edit',
                    command: 'handleEdit',
                    content: '',
                },
                {
                    icon: 'Open',
                    status: "1",
                    type:0,
                    command: 'handleSwitch',
                    content: '',
                },
                {
                    icon: 'Delete',
                    command: 'deleteBox',
                    content: '',
                }
            ]
        }
    ],
    data: [],
    config: {
        isSelection: false,
        isList: false,
        isPagination: true, // 是否分页
        total: 0, // 总条数
        loading: false
    },
    rolePermissionList: rolePermissionList.value// 角色权限列表
})
onActivated(() => {
    getPermission()
    getUserList()
})
// 删除用户
const deleteBox = (row) => {
    ElMessageBox.confirm(
        '确认删除该条用户信息吗？',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        deleteUser(row.id).then((res) => {
            if (res.code == '00000') {
                getUserList()
                ElMessage.success('删除成功')
            } else {
                ElMessage.warning(res.msg)
            }
        })
    })
        .catch(() => {
            ElMessage.info('取消删除')
        })
}
//修改账号状态
const handleSwitch = (rowId, statu) => {
    if (rowId) {
        modifyStatus(rowId, statu).then(res => {
            console.log(res)
            if (res.code == '00000') {
                getUserList()
                ElMessage.success('状态修改成功')
            } else {
                ElMessage.error(res.msg)
            }

        }, err => {
            console.log(err)
        })

    } else {
        ElMessage.warning('状态修改失败')
    }
}
//详情查询
const getRoleDetail=(row)=>{
  getRoleDetailById(row).then(res => {
   form.value=res.data
    console.log('form.value',form.value)
     let roleId=res.data.roleId.split(",") || []
    let roleIdList=[]
    roleId.forEach((item)=>{
      roleIdList.push(parseInt(item))
    })
    form.value.roleId=roleIdList

  })
}
//获取角色权限列表
const getPermission = () => {
    getRolePermission({}).then(res => {
        if (res.data) {
            rolePermissionList.value = res.data
            tableDta.rolePermissionList = res.data
        }
    })
}

// 获取手机/邮箱 验证码
const getCode = (type) => {
    if (type == 'phone' && form.value.mobile) {
         if(!form.value.mobile){
                ElMessage.warning("请输入手机号");
                return false
            }
            const data = {
                "mobile": form.value.mobile
            }
        getPhoneCode(data).then(res => {
            console.log(res)
            if (res.code == "00000") {
                ElMessage.success('发送成功')
                sendVerificationCode(type)

            }
        })
    } else if (type == 'email' && form.value.email) {
        if(!form.value.email){
                ElMessage.warning("请输入邮箱地址");
                return false
            }
        getEmailCode(form.value.email).then(res => {
            console.log(res)
            if (res.code == "00000") {
                ElMessage.success('发送成功')
                sendVerificationCode(type)
            }
        })
    } else {
        ElMessage.warning('请检查手机号或邮箱是否填写正确')
    }
}
// 倒计时的秒数
const countdownPhone = ref(0);
const countdownEmail = ref(0);


// 发送验证码函数
const sendVerificationCode = (type) => {
   // 如果倒计时已经开始，则直接返回
   if(type=='phone'){
    if (countdownPhone.value > 0) return;

    // 设置倒计时为60秒
    countdownPhone.value = 60;
    // 启动定时器，每秒减少一秒
    const timer = setInterval(() => {
      countdownPhone.value--;
        // 当倒计时结束时，清除定时器
        if (countdownPhone.value === 0) {
          clearInterval(timer);
        }
    }, 1000)
   }else if(type=='email'){
    if (countdownEmail.value > 0) return;

    // 设置倒计时为60秒
    countdownEmail.value = 60;
    // 启动定时器，每秒减少一秒
    const timer = setInterval(() => {
      countdownEmail.value--;
        // 当倒计时结束时，清除定时器
        if (countdownEmail.value === 0) {
          clearInterval(timer);
        }
    }, 1000)
   }
   
  
}
const queryRef=ref(null)

//清空所有填写搜索信息
const resetFrome = () => {
     queryRef.value.resetFields()
    queryParams.value.createStartTime=''
    queryParams.value.createEndTime=''
    queryParams.value.examineStartTime=''
    queryParams.value.examineEndTime=''
    getUserList()
}
// 验证两次密码是否一致
const checkpassword = () => {
    if (form.value.password !== form.value.confirmPassword) {
        ElMessage.error('两次密码不一致,请重新输入')
        form.value.confirmPassword = ''
        return false
    }

}
const typeOpen=ref(1)
const dialogVisible=ref(false)
// 新增用户弹窗
const setNewUser = () => {
   typeOpen.value=1
    dialogVisible.value = true
}
// 编辑
const handleEdit = (row) => {
  console.log('编辑', row)
   typeOpen.value=2
   getRoleDetail(row)
    dialogVisible.value=true
}

/** 提交按钮 */
const submitForm = (formEl: FormInstance | undefined) =>{
  if (!formEl) return
  formEl.validate(valid => {
   if(form.value.password!=form.value.confirmPassword){
      ElMessage.warning("两次输入的密码不一致！");
      return false
   }
   let dataForm=JSON.parse(JSON.stringify(form.value))
   if(dataForm.roleId.length>0){
    dataForm.roleId=dataForm.roleId.join(',')
   }
   console.log('dataForm',dataForm)
    if (valid) {
        dataForm.userType=3
      if (form.value.id != undefined) {
        dataForm.userId=dataForm.id
        saveUserInfo(dataForm).then(response => {
          cancel();
            ElMessage.success('编辑用户成功')

          getUserList()
        });
      } else {
        addUser(dataForm).then(response => {
          cancel();
        ElMessage.success('新增用户成功')
          getUserList()
      
        });
      }
    }
  });
};
//关闭弹框
const cancel = () => {
  typeOpen.value=1
  userRef.value.resetFields()// 重置数据
  form.value={}
  dialogVisible.value=false
}
// 查询列表
const getUserList = () => {
    getUserPage(queryParams.value).then(res => {
        tableDta.data = res.data.list
        tableDta.config.total = res.data.total
    })
}

// 分页切换
const tabPageChange = (val) => {
    queryParams.value.pageNum = val.pageNum
    queryParams.value.pageSize = val.pageSize
    getUserList()
}
</script>
<style lang="scss" scoped>
.addUser {
    height: 40px;
    margin: 20px 0;

}
</style>
